import os
import threading

import cx_Oracle

from util.comm.msg_util import msg
from util.env.java.jar_util import delayed_open_url

# 定义一个连接池
conn_map = {}

class MyOracle():
    def __init__(self):
        super().__init__()

    def search(self, config, sql):
        # 获取数据库连接
        conn = self.connect(config)

        if conn is None:
            return None

        # 创建游标
        cursor = conn.cursor()

        # 执行查询语句
        cursor.execute(sql)

        field_list = []
        # 获取查询结果
        for row in cursor:
            field_list.append(row)

        # cursor.close()

        return field_list

    def searchObj(self, config, sql):
        # 获取数据库连接
        conn = self.connect(config)

        if conn is None:
            return None

        # 创建游标
        cursor = conn.cursor()

        # 执行查询语句
        cursor.execute(sql)

        # 获取列的名称
        column_names = [desc[0].lower() for desc in cursor.description]

        field_list = []
        # 获取查询结果
        for row in cursor:
            field_list.append({col: value for col, value in zip(column_names, row)})

        # cursor.close()

        return field_list

    def connect(self, config):
        # 创建数据库连接
        oracle_home = os.environ.get('ORACLE_HOME')
        if oracle_home is None:
            msg("缺少oracle环境,请配置环境,地址：https://blog.csdn.net/kay_lew/article/details/135577303")
            url = "https://blog.csdn.net/kay_lew/article/details/135577303"
            threading.Thread(target=delayed_open_url, args=(url, 2,)).start()
            return "0"

        try:
            cx_Oracle.init_oracle_client(lib_dir=r"%s" % oracle_home)
        except:
            pass

        conn_str = '%s/%s@%s:%s/%s' % (config['user'], config['password'], config['host'], config['port'], config['service_name'])
        if conn_map.get(conn_str) is not None:
            conn = conn_map[conn_str]
            # 判断连接是否可用
            try:
                conn.ping()
                return conn
            except cx_Oracle.DatabaseError as e:
                print("oracle连接失败，请检查连接配置; %s" % e)
                pass

        try:
            conn = cx_Oracle.connect(conn_str)
        except cx_Oracle.DatabaseError as e:
            msg("oracle连接失败，请检查连接配置; %s" % e)
            return None

        conn_map[conn_str] = conn
        return conn

    def distory(self):
        for conn in conn_map.values():
            print("关闭连接")
            conn.close()
            conn_map.clear()